#include "telem.h"
#include <sstream>

using namespace std;


void TElem::ujatri(string nev,string ertek){
    bool l=false;
    for(vector<Atributum>::iterator it = atributumok.begin(); it != atributumok.end() && !l; ++it){
        l = it->nev == nev;
    }
    if(!l){
        Atributum seged;
        seged.nev = nev; seged.ertek = ertek;
        atributumok.push_back(seged);
    }else { throw ATRI_EXIST;}
}

void TElem::modatri(std::string nev, std::string ertek){
    if (atributumok.size() > 0){
        bool l=false;
        int i = 0;
        for(; i < atributumok.size() && !l; ++i){
            l = atributumok[i].nev == nev;
        }
        if (l){
            atributumok[i-1].ertek = ertek;
        }else { throw ATRI_NEXIST;}
    }else {throw ATRI_NEXIST;}
}

void TElem::torlesatri(std::string nev){
    if (atributumok.size() > 0){
        bool l=false;

        for(vector<Atributum>::iterator it = atributumok.begin();
        it !=  atributumok.end() && !l; ++it){

            if (l = (it->nev == nev)){atributumok.erase(it);}
        }
        if (!l){ throw ATRI_NEXIST;}
    }else { throw ATRI_NEXIST;}
}

void TElem::ujgyerek(Tag &uj){
    //std::vector<Tag*> gyerekek;
    gyerekek.push_back(&uj);
}

TElem::~TElem(){
    for(vector<Tag*>::iterator it = gyerekek.begin(); it != gyerekek.end();){
        Tag* t = *it;
        ++it;
        delete t;
    }
}


void TElem::modosit(std::string nev){
    TElem::nev = nev;
}

string TElem::konzolrair(){
    ostringstream os;
    os << "Elem neve: " << nev << endl;
    os << "Atributumok: " << endl;
    for (vector<Atributum>::iterator it = atributumok.begin();it != atributumok.end(); ++it){
        os << it->nev << "=\""<< it->ertek << "\"\t";
    }
    if (gyerekek.size() == 0){
        os << endl <<"Nincs gyereke." << endl;
    }else {
        os << "Gyerekek: " << endl;
        for(int i = 0; i < gyerekek.size();++i){
        os << i+1 << " gyerek neve: " << gyerekek[i]->getname() << endl;
        }
    }
    return os.str();
}

string TElem::toString(){
    ostringstream os;
    os << "<" << nev;
    for (vector<Atributum>::iterator it = atributumok.begin(); it != atributumok.end(); ++it){
        os << " " << it->nev << "=\""<< it->ertek << "\"";
    }
    if (gyerekek.size() == 0){
        os << "/>";
    }else {
        os << ">" << endl;
        for(vector<Tag*>::iterator it = gyerekek.begin();it != gyerekek.end();++it){
        os << (*it)->toString() << endl;
        }
        os << "</" << nev << ">";
    }
    return os.str();
}
